#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Sample for AppEngine-OAuth on Google App Engine
 
See: http://0-oo.net/sbox/python-box/appengine-oauth
See also: http://apiwiki.twitter.com/OAuth-FAQ
'''
 
import sys, os
import logging
import wsgiref.handlers
from appengine_twitter import AppEngineTwitter
from basehandler import BaseHandler, h
from django.utils import simplejson
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template 
from google.appengine.api import urlfetch
 
OAUTH_KEY = 'wKYvS5KnPHyh4aiA2gRjqQ'
OAUTH_SECRET = 'K0Ot3X27pQ7i377fDIj1QqzzeNu8ozymtWurKvjGhQ'
 
 
class DemoHandler(BaseHandler):
 
  def demo_header(self):
    self.simple_header(u'AppEngine-OAuthのデモ')
 
    self.p(u'<h1>AppEngine-OAuthのデモ</h1>')
 
 
  def demo_footer(self):
    self.p('<br>')
    self.p('<hr>', True)
    self.p(u'このページは')
    self.p('<a href="http://0-oo.net/sbox/python-box/appengine-oauth">')
    self.p(u'AppEngine-OAuth</a> と ')
    self.p('<a href="http://0-oo.net/sbox/python-box/appengine-twitter">')
    self.p(u'AppEngine-Twitter</a> のデモです')
 
    self.simple_footer()
 
 
 
class InitHandler(DemoHandler):
 
  def get(self):
    sys.stderr.write("InitHandler.get")
    twitter = AppEngineTwitter()
    twitter.set_oauth(key=OAUTH_KEY, secret=OAUTH_SECRET)
 
    req_info = twitter.prepare_oauth_login()
 
    # request_tokenはcallbackされた後で使うのでDatastoreに保存しておく
    OAuthRequestToken(token=req_info['oauth_token'],
                      secret=req_info['oauth_token_secret']).put()
 
    self.demo_header()
    self.p('<a href="' + h(req_info['url']) + '">')
    self.p(u'TwitterのOAuthログインへ</a>', True)
    self.demo_footer()
 
 
 
class CallbackHandler(DemoHandler):
 
  def get(self):
    twitter = AppEngineTwitter()
    twitter.set_oauth(OAUTH_KEY, OAUTH_SECRET)
 
    # TwitterからHTTP GETでrequest_tokenが渡される
    req_token = self.request.get('oauth_token')
 
    # Datastoreに保存しておいたreqest_token_secretを取り出す
    query = OAuthRequestToken.all()
    query.filter('token = ', req_token)
    req_tokens = query.fetch(1)
 
    # request_tokenとaccess_tokenを交換する
    res = twitter.exchange_oauth_tokens(req_token, req_tokens[0].secret)

#     twitter.verify()
#     user_screen_name = simplejson.loads(twitter.last_response.content)['screen_name']
#     user_id = simplejson.loads(twitter.last_response.content)['id']

    template_values = {
      'twitter_access_token': res['oauth_token'],
      'twitter_access_token_secret': res['oauth_token_secret'],
      'twitter_user_screen_name': res['screen_name'],
      'twitter_user_id': res['user_id'],
      }

    template_path = os.path.join(os.path.dirname(__file__), 'callback_template.html')
    self.response.out.write(template.render(template_path, template_values))


class ProxyHandler(DemoHandler):
  def get(self):
    twitter = AppEngineTwitter()
    twitter.set_oauth(OAUTH_KEY, OAUTH_SECRET)

    path_array = self.request.path.split("/")
    path_array.pop(0)
    path_array.pop(0)
    path = "/".join(path_array)

    url = 'http://twitter.com/' + path + '?' + self.request.query_string
    res = urlfetch.fetch(url=url, method='GET')

    self.p(res.content, True)
    
 
 
#Model(s)
 
class OAuthRequestToken(db.Model):
  token = db.StringProperty()
  secret = db.StringProperty()
 
 
 
logging.getLogger()
routing = [('/', InitHandler),
           ('/callback', CallbackHandler),
           ('/proxy/.*', ProxyHandler)]
application = webapp.WSGIApplication(routing, debug=False)
wsgiref.handlers.CGIHandler().run(application)
